package com.simple.microservices.manager;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.PhoneUtil;
import com.simple.microservices.api.auth.AuthService;
import com.simple.microservices.api.dto.LoginDTO;
import com.simple.microservices.commons.exceptions.BusinessException;
import com.simple.microservices.dao.dataobject.Member;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
@Slf4j
@Component
public class AuthManager {

    @Resource
    private AuthService authService;
    /**
     * 登录
     * @param loginDTO
     * @param request
     * @param response
     */
    public void login(LoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
        String token = authService.login(loginDTO);
        response.addHeader("token", token);
    }

    /**
     * 登陆校验
     * @param cellphone
     * @param code
     * @param request
     * @param response
     */
    public void login(String cellphone, String code, HttpServletRequest request, HttpServletResponse response) {
        log.info("登陆={}", DesensitizedUtil.mobilePhone(cellphone));
        Boolean checkCodeFlag = authService.checkCode(cellphone,code);
        if (!checkCodeFlag){
            throw new BusinessException("验证码错误");
        }
        Member rsp = authService.findMemberByCellphone(cellphone);
        if (rsp==null){
            Member req = new Member();
            req.setCellphone(cellphone);
            String pass = cellphone.substring(5, 11);
            req.setPassword(pass);
            req.setUsername(cellphone);
            authService.saveMember(req);
        }
        String token = authService.login(cellphone,rsp.getId());
        response.addHeader("token",token);

    }

    /**
     * 发送验证码
     * @param cellphone
     */
    public void sendCode(String cellphone) {
        log.info("发送验证码={}", DesensitizedUtil.mobilePhone(cellphone));
        authService.sendCode(cellphone);
    }
}
